package com.shengwei.truck.driver.vm;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import android.app.Application;
import com.shengwei.truck.driver.view.ui.app.MyApplication;
import com.shengwei.truck.driver.bean.JsonLoginData;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.model.Repository;

/**
 * 登录页面的VM层，调用M层去获取数据，同时更改liveData的数据，从而View层（LoginActivity)就能观察到LiveData数据的
 * 变化，最后更新UI。
 */
public class LoginViewModel extends AndroidViewModel {

    String TAG = "LoginViewModel";
    private MutableLiveData<Result<JsonLoginData>> jsonLoginLiveData = new MutableLiveData<>();
    private MutableLiveData<Result<String>> logoutLiveData = new MutableLiveData<>();
    private Repository mRepository; //M层引用
    private MyApplication mApp;

    /**
     * 构造函数
     * @param app：为了防止内存泄露，传递一个Application作为context
     * @param Repository: M层对象实例
     */
    public LoginViewModel(Application app,Repository Repository) {
        super(app);
        this.mApp = getApplication();
        this.mRepository = Repository;
    }

    public MutableLiveData<Result<String>> getLogoutLiveData() { return logoutLiveData; }
    public MutableLiveData<Result<JsonLoginData>> getJsonLogin() {
        return jsonLoginLiveData;
    }
    /**
     * VM层调用M层（Repository+DataSource）
     * @param username： 用户名
     * @param password： 密码
     * @return
     */
    public MutableLiveData<Result<JsonLoginData>> login(String username, String password) {
        jsonLoginLiveData = mRepository.login(username, password,jsonLoginLiveData,mApp);
        return jsonLoginLiveData;
    }

    /**
     * 退出登录
     */
    public void logout() {
        mRepository.logout(logoutLiveData);
    }
}